from dateutil.relativedelta import relativedelta
from tortoise.expressions import Q, F

from app.controllers.marketing.integral import integral_controller
from app.core.crud import CRUDBase
from datetime import datetime, date, timedelta
from app.models.checkin import Checkin
from app.schemas.checkin import CheckinCreate, CheckinUpdate
from app.schemas.marketing import IntegralCreate


class CheckinController(CRUDBase[Checkin, CheckinCreate, CheckinUpdate]):
    def __init__(self):
        super().__init__(model=Checkin)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs = await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at", "deleted_at"]) for obj in objs]

        return total, data

    async def do_create(self, obj_in: CheckinCreate):
        today = date.today()
        next_day = today + timedelta(days=1)
        checkin_data = await Checkin.filter(user_id=obj_in.user_id,
                                            checkin_time__gte=datetime(today.year, today.month, today.day),
                                            checkin_time__lt=datetime(next_day.year, next_day.month, next_day.day)
                                            ).first().values("id")

        if checkin_data:
            return False
        else:
            await self.create(obj_in=obj_in)
            # new_time = obj_in.checkin_time + relativedelta(years=1)
            integral = IntegralCreate(
                user_id=obj_in.user_id,
                price=1,
                direction=1,
                type=3,
                type_id=0,
                expire_at=None,
                remark='签到积分增加',
            )
            await integral_controller.do_create(obj_in=integral)
            return True


checkin_controller = CheckinController()
